import os
import execjs
import requests
import pandas as pd

jsl_user = '17600102606'
jsl_psd = "jslLjblv@321"

filename = 'encode_jsl.txt'

path = os.path.dirname(os.path.abspath(filename))
full_path = os.path.join(path, filename)

headers = {
    'Host': 'www.jisilu.cn', 'Connection': 'keep-alive', 'Pragma': 'no-cache',
    'Cache-Control': 'no-cache', 'Accept': 'application/json,text/javascript,*/*;q=0.01',
    'Origin': 'https://www.jisilu.cn', 'X-Requested-With': 'XMLHttpRequest',
    'User-Agent': 'Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/67.0.3396.99Safari/537.36',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'Referer': 'https://www.jisilu.cn/login/',
    'Accept-Encoding': 'gzip,deflate,br',
    'Accept-Language': 'zh,en;q=0.9,en-US;q=0.8'
}


def decoder(text):
    key = '397151C04723421F'
    with open(full_path, 'r', encoding='utf-8') as f:
        source = f.read()
        ctx = execjs.compile(source)
        return ctx.call('jslencode', text, key)

    """
    登录
    把 cookis 保存到本地，每次判断 cookie 是否过期，没有过期的话，直接使用，过期的话，调用登录接口
    """


def login(user, password):
    session = requests.Session()
    url = "https://www.jisilu.cn/account/ajax/login_process/"
    username = decoder(user)
    jsl_password = decoder(password)
    data = {
        'return_url': 'https://www.jisilu.cn/',
        'user_name': username,
        'password': jsl_password,
        'net_auto_login': '1',
        '_post_type': 'ajax',
    }

    js = session.post(url=url, headers=headers, data=data)

    ret = js.json()

    if ret.get('errno') == 1:
        print('login success')
        return session
    else:
        print('login failed')
        raise ValueError('login failed')


def main():
    session = login(jsl_user, jsl_psd)
    jslPd = getJslData(session)
    # 忽略掉还没有上市的可转债
    jslPd.drop(jslPd[(jslPd['剩余年限']==6.00)|(jslPd['评级'] == 'CC')].index, inplace=True)
    # jslPd.drop(jslPd[(jslPd['评级'] == 'CC')].index, inplace=True)
    # jslPd.drop(jslPd[(jslPd['评级'] == 'CC')].index, inplace=True)
    jslPd.sort_values(by=["转股溢价率"], inplace=True)
    print(jslPd)

    """
    获取集思录的可转债数据
    """


def getJslData(session):
    # 登陆后要爬取https://www.jisilu.cn/data/cbnew/cb_list_new/的数据，修改下面代码
    # headers_jsl={
    # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110Safari/537.36',
    # 'Cookie': '; '.join([str(x['name']) + '=' + str(x['value']) for x in cookie])
    # }
    url = 'https://www.jisilu.cn/data/cbnew/cb_list_new/'
    session
    response = session.get(url, headers=headers)
    data = response.json()
    df = pd.DataFrame(data["rows"])["cell"].apply(pd.Series)
    df = df.rename(
        columns={
            "bond_id": "代码",
            "bond_nm": "转债名称",
            "price": "现价",
            "increase_rt": "涨跌幅",
            "stock_id": "正股代码",
            "stock_nm": "正股名称",
            "sprice": "正股价",
            "sincrease_rt": "正股涨跌",
            "pb": "正股PB",
            "convert_price": "转股价",
            "convert_value": "转股价值",
            "premium_rt": "转股溢价率",
            "dblow": "双低",
            "rating_cd": "评级",
            "put_convert_price": "回售触发价",
            "force_redeem_price": "强赎触发价",
            "convert_amt_ratio": "转债流通市值占比",
            "maturity_dt": "到期时间",
            "year_left": "剩余年限",
            "curr_iss_amt": "剩余规模-亿",
            "volume": "成交额-万",
            "turnover_rt": "换手率",
            "ytm_rt": "到期税前收益",
            "real_force_redeem_price": "实时赎回价",
            "ref_yield_info": "纯债价值",
            "option_tip": "期权价值"
        },  # 对索引进行重命名
    )
    # df = df.drop(columns=['id'])        # 删除特定的列
    df = df[
        [
            "代码",
            "转债名称",
            "现价",
            "涨跌幅",
            "正股代码",
            "正股名称",
            "正股价",
            "正股涨跌",
            "正股PB",
            "转股价",
            "转股价值",
            "转股溢价率",
            "双低",
            "评级",
            "回售触发价",
            "强赎触发价",
            "转债流通市值占比",
            "到期时间",
            "剩余年限",
            "剩余规模-亿",
            "成交额-万",
            "换手率",
            "到期税前收益",
            "实时赎回价",
            "纯债价值",
            "期权价值"
        ]
    ]  # 保留的数据
    return df


if __name__ == '__main__':
    main()
